package com.gxsyh.nantie.login.provider.service.impl;

import com.google.common.collect.Lists;
import com.gxsyh.nantie.login.provider.domain.TbPermission;
import com.gxsyh.nantie.login.provider.domain.TbUser;
import com.gxsyh.nantie.login.provider.service.TbPermissionService;
import com.gxsyh.nantie.login.provider.service.TbUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/1/19
 * @time: 17:03
 * @Description:
 */
@Component
public class MyUserDetailsServiceImpl  implements UserDetailsService {
    @Resource
    TbUserService tbUserService;

    @Resource
    TbPermissionService tbPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser = tbUserService.selectOneTbUserById(Long.valueOf(username));
        List<GrantedAuthority> grantedAuthorities= Lists.newArrayList();

        if (tbUser!=null)
        {
            List<TbPermission> tbPermissions = tbPermissionService.selectTbPermissionByUsername(tbUser.getUsername());
            tbPermissions.forEach(tbPermission -> {
                if (tbPermission!=null&&tbPermission.getEnname()!=null)
                {
                    GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }


        return new User(tbUser.getId().toString(),tbUser.getPassword(),grantedAuthorities);
    }
}
